<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use Toplan\PhpSms\Sms;
use DB;
use Auth;
use Validator;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Agent;
use App\User;
use App\Region;
use App\PhoneValidate;
use App\WxPublicUser;
use App\UserStatistic;
use App\WinnerNotice;
use App\Club;
use App\ClubUser;
use App\SuperAgent;

class HomeController extends Controller
{

	protected $config = [
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',

	    // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
	    'response_type' => 'array',

	    'log' => [
	        'level' => 'debug',
	        'file' => __DIR__.'/wechat.log',
	    ],
	    /**
	     * OAuth 配置
	     *
	     * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
	     * callback：OAuth授权完成后的回调页地址
	     */
	    'oauth' => [
	        'scopes'   => ['snsapi_userinfo'],
	        'callback' => '/mobile/callback',
	    ],
	];
	/**
	 * [index description]
	 * @return [type] [description]
	 */
	public function index(Request $request)
	{
		if ($request->input('aid')) {
			Session::put('superagent_id', $request->input('aid'));
		}
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->redirect();
        return $response;
	}

	/**
	 * [iphone description]
	 * @return [type] [description]
	 */
	public function iphone()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'FIRST_GUID'])->redirect();
        return $response;
		// return view('mobile.agent.iphone');
	}

	/**
	 * [bindAgent description]
	 * @return [type] [description]
	 */
	public function bindAgent(Request $request)
	{
		if ($request->input('aid')) {
			Session::put('shareid', $request->input('aid'));
			$app = new Application($this->config);
			$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'SHARE'])->redirect();
	        return $response;
		}
	}

	/**
	 * 三级代理发展二级代理
	 */
	public function secondDvlp(Request $request)
	{
		if ($request->input('aid')) {
			Session::put('second_dvlp_agentid', $request->input('aid'));
			$app = new Application($this->config);
			$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'SECONDDVLP'])->redirect();
	        return $response;
		}
	}

	/**
	 * [downloadAgent description]
	 * @return [type] [description]
	 */
	public function downloadAgent(Request $request)
	{
		if ($request->input('aid')) {
			Session::put('agentid', $request->input('aid'));
			$app = new Application($this->config);
			$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'AGENT'])->redirect();
	        return $response;
		}
	}

	/**
	 * [bindSecond description]
	 * @return [type] [description]
	 */
	public function bindSecond(Request $request)
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'BIND_SECOND'])->redirect();
	    return $response;
	}

	/**
	 * [ticket 领取每日银票]
	 * @return [type] [description]
	 */
	public function ticket()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'TICKET'])->redirect();
	    return $response;
	}

	/**
	 * [download 下载游戏]
	 * @return [type] [description]
	 */
	public function download()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'DOWNLOAD_GAME'])->redirect();
	    return $response;
	}

	/**
	 * [wcChampion 冠军竞猜]
	 * @return [type] [description]
	 */
	public function wcChampion()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'WC_CHAMPION'])->redirect();
	    return $response;
	}

	/**
	 * [wcDayguess 每日竞猜]
	 * @return [type] [description]
	 */
	public function wcDayguess()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'WC_DAYGUESS'])->redirect();
	    return $response;
	}

	/**
	 * [inviteFriend 邀请用户加入亲友圈]
	 * @return [type] [description]
	 */
	public function inviteFriend(Request $request)
	{
		if ($request->input('cid') && $request->input('aid')) {
			Session::put('wx_invite_club_id', $request->input('cid'));
			Session::put('wx_invite_agent_id', $request->input('aid'));
			$app = new Application($this->config);
			$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'INVITE_FRIEND'])->redirect();
		    return $response;
		} else {
			return view('admin.layout.unfind');
		}
	}

	/**
	 * [wxShare 发送朋友或朋友圈]
	 * @return [type] [description]
	 */
	public function wxShare(Request $request)
	{
		if ($request->input('aid')) {
			Session::put('wx_menu_share_id', $request->input('aid'));
			$app = new Application($this->config);
			$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'MENU_SHARE'])->redirect();
		    return $response;
		}
	}

	/**
	 * [drawLottery 转盘抽奖]
	 * @return [type] [description]
	 */
	public function drawLottery(Request $request)
	{
		if ($request->input('invite_id')) {
			Session::put('wx_share_lottery_invite_id', $request->input('invite_id'));
		}
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'DRAW_LOTTERY'])->redirect();
	    return $response;
	}

	/**
	 * [dayPay 每日支付]
	 * @return [type] [description]
	 */
	public function dayPay()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'DAY_PAYMENT'])->redirect();
	    return $response;
	}

	/**
	 * [superAgentApply 超级代理申请]
	 * @return [type] [description]
	 */
	public function superAgentApply()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'SUPER_AGENT_APPLY'])->redirect();
	    return $response;
	}

	/**
	 * [agentLogin description]
	 * @return [type] [description]
	 */
	public function agentLogin()
	{
		$app = new Application($this->config);
		$response = $app->oauth->scopes(['snsapi_userinfo'])->with(['state' => 'AGENT_LOGIN'])->redirect();
	    return $response;
	}

	/**
	 * [callback description]
	 * @return function [description]
	 */
	public function callback()
	{
		$app = new Application($this->config);
		$user = $app->oauth->user();
		$origin_info = $user->getOriginal();
		if (isset($_REQUEST['state']) && $_REQUEST['state'] == 'SHARE') {//代理分享
			$shareid = Session::get('shareid');
			if ($shareid) {
				if ($origin_info) {
					$agent = Agent::where(['unionid' => $origin_info['unionid']])->first();
					if ($agent) {//如果已经是一个代理
						return redirect('/mobile/agent/index/'.$agent->id);//去代理首页
					} else {
						$agent = Agent::where(['id' => $shareid])->first();
						if ($agent) {
							if ($agent->pid == 0) {//受邀成为二级代理
								$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
								if ($user) {//如果已经是游戏用户了，进入二级代理申请页面

									return view('mobile.agent.secondapply', compact('origin_info', 'agent'));
								} else {//如果是一个新用户，注册用户，并进入二级代理申请页面
					        		$user = new User;
					        		$user->userid = $this->generateUserId();
					        		$user->account = 'wx_'.$origin_info['unionid'];
					        		$user->open_id = $origin_info['openid'];
					        		$user->nickname = $origin_info['nickname'];
					        		$user->headimg = $origin_info['headimgurl'];
					        		$user->name = base64_encode($origin_info['nickname']);
					        		$user->lv = 1;
					        		$user->coins = 1000;
					        		$user->gems = 10;
					        		$user->is_new = 1;
					        		$user->save();

					        		return view('mobile.agent.secondapply', compact('origin_info', 'agent'));
								}
							} else {//受邀成为普通用户
								$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
								if ($user) {//如果已经是游戏用户了
									if ($user->daili_id != 0) {//没有绑定过代理
										$user->daili_id = $agent->id;
										$user->save();
										return view('mobile.agent.download');//去游戏下载页面
									} else {//已经绑定过代理了，不能重复绑定
										$message = "您已经绑定过代理了，不能重复绑定!";
										return view('mobile.agent.errormsg', compact('message'));
									}
								} else {//是一个新用户，注册而成为游戏用户
					        		$user = new User;
					        		$user->userid = $this->generateUserId();
					        		$user->account = 'wx_'.$origin_info['unionid'];
					        		$user->open_id = $origin_info['openid'];
					        		$user->nickname = $origin_info['nickname'];
					        		$user->headimg = $origin_info['headimgurl'];
					        		$user->name = base64_encode($origin_info['nickname']);
					        		$user->lv = 1;
					        		$user->coins = 1000;
					        		$user->gems = 10;
					        		$user->is_new = 1;
					        		$user->daili_id = $agent->id;
					        		$user->save();
					        		return redirect('/mobile/home/download/'.$user->id);
								}
							}
						}
					}
				}
			}
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'SECONDDVLP') {
			$shareid = Session::get('second_dvlp_agentid');
			if ($shareid) {
				if ($origin_info) {
					$agent = Agent::where(['unionid' => $origin_info['unionid']])->first();
					if ($agent) {//如果已经是一个代理
						return redirect('/mobile/agent/index/'.$agent->id);//去代理首页
					} else {
						$agent = Agent::where(['id' => $shareid])->first();
						if ($agent) {
							if ($agent->level == 2) {//受邀成为三级代理
								$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
								if ($user) {//如果已经是游戏用户了，进入三级代理申请页面

									return view('mobile.agent.threeapply', compact('origin_info', 'agent'));
								} else {//如果是一个新用户，注册用户，并进入三级代理申请页面
					        		$user = new User;
					        		$user->userid = $this->generateUserId();
					        		$user->account = 'wx_'.$origin_info['unionid'];
					        		$user->open_id = $origin_info['openid'];
					        		$user->nickname = $origin_info['nickname'];
					        		$user->headimg = $origin_info['headimgurl'];
					        		$user->name = base64_encode($origin_info['nickname']);
					        		$user->lv = 1;
					        		$user->coins = 1000;
					        		$user->gems = 10;
					        		$user->is_new = 1;
					        		$user->save();

					        		return view('mobile.agent.threeapply', compact('origin_info', 'agent'));
								}
							}
						}
					}
				}
			}
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'AGENT') {//扫码代理分享
			$agentid = Session::get('agentid');
			if ($agentid) {
				if ($origin_info) {
					$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
					if ($user) {//已经是游戏用户了
						$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
						if ($wx_fans) {
							$wx_fans->unionid = $origin_info['unionid'];
							$wx_fans->agent_id = $agentid;
							$wx_fans->nickname = $origin_info['nickname'];
							$wx_fans->headimgurl = $origin_info['headimgurl'];
							$wx_fans->save();
						}
					} else {
		        		$user = new User;
		        		$user->userid = $this->generateUserId();
		        		$user->account = 'wx_'.$origin_info['unionid'];
		        		$user->open_id = $origin_info['openid'];
		        		$user->nickname = $origin_info['nickname'];
		        		$user->headimg = $origin_info['headimgurl'];
		        		$user->name = base64_encode($origin_info['nickname']);
		        		$user->daili_id = $agentid;
		        		$user->lv = 1;
		        		$user->coins = 1000;
		        		$user->gems = 10;
		        		$user->is_new = 1;
		        		$user->save();
						$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
						if ($wx_fans) {
							$wx_fans->unionid = $origin_info['unionid'];
							$wx_fans->agent_id = $agentid;
							$wx_fans->nickname = $origin_info['nickname'];
							$wx_fans->headimgurl = $origin_info['headimgurl'];
							$wx_fans->save();
						}
						$agent = Agent::where(['id' => $user->daili_id])->first();
						if ($agent) {
					        $app = new Application($this->config);
				            $notice = $app->notice;
				            $openId = $agent->open_id;
    		            	$userService = $app->user;
				            $member = $userService->get($openId);
				            $subscribe = $member->subscribe;
				            if ($subscribe) {
					            $templateId = 'ThzL02D7i_RDlU2_qaKRbqcahMIUWRp4yOlHICEwlHo';
					            $url = url("/mobile/index");
					            $data = array(
					                "first" => "有新玩家与您成功完成绑定!",
					                "keyword1" => $user->nickname,
					                "keyword2" => date('Y-m-d H:i', time()),
					                "remark" => "查看详情!",
					            );
					            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
					        }    	
						}
					}
					return redirect('/mobile/home/download/'.$user->id);	
				}
			}	
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'BIND_SECOND') {//绑定二级代理
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if (!$user) {
	        		$user = new User;
	        		$user->userid = $this->generateUserId();
	        		$user->account = 'wx_'.$origin_info['unionid'];
	        		$user->open_id = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimg = $origin_info['headimgurl'];
	        		$user->name = base64_encode($origin_info['nickname']);
	        		$user->lv = 1;
	        		$user->coins = 1000;
	        		$user->gems = 10;
	        		$user->is_new = 1;
	        		$user->save();
					$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
					if ($wx_fans) {
						$wx_fans->unionid = $origin_info['unionid'];
						$wx_fans->nickname = $origin_info['nickname'];
						$wx_fans->headimgurl = $origin_info['headimgurl'];
						$wx_fans->save();
					}
				}
				return redirect('/mobile/enter_agent/'.$user->id);
			}	
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'TICKET') {//领取每日银票
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if (!$user) {//还未注册
					return redirect('http://fir.im/91z4');//引导用户下载游戏
				} else {
					return redirect('/mobile/ticket/index/'.$user->id);//引导用户去领取银票
				}
			}	
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'FIRST_GUID') {//初次进入公众号的用户，同步用户信息
			if ($origin_info) {
				$user = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
				if (!$user) {
	        		$user = new WxPublicUser;
	        		$user->unionid = $origin_info['unionid'];
	        		$user->openid = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimgurl = $origin_info['headimgurl'];
	        		$user->save();
				} else {
					$user->unionid = $origin_info['unionid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimgurl = $origin_info['headimgurl'];
	        		$user->save();
				}
				return view('mobile.agent.iphone');
			}	
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'DOWNLOAD_GAME') {//下载游戏
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if ($user) {//如果已经是游戏用户了
					$wx_user = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
					if ($wx_user) {//已经是公众号用户
		        		$wx_user->unionid = $origin_info['unionid'];
		        		$wx_user->nickname = $origin_info['nickname'];
		        		$wx_user->headimgurl = $origin_info['headimgurl'];
		        		$wx_user->save();
					} else {//注册公众号
		        		$wx_user = new WxPublicUser;
		        		$wx_user->unionid = $origin_info['unionid'];
		        		$wx_user->openid = $origin_info['openid'];
		        		$wx_user->nickname = $origin_info['nickname'];
		        		$wx_user->headimgurl = $origin_info['headimgurl'];
		        		$wx_user->save();
					}
				} else {//是一个新用户，注册而成为游戏用户
	        		$user = new User;
	        		$user->userid = $this->generateUserId();
	        		$user->account = 'wx_'.$origin_info['unionid'];
	        		$user->open_id = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimg = $origin_info['headimgurl'];
	        		$user->name = base64_encode($origin_info['nickname']);
	        		$user->lv = 1;
	        		$user->coins = 1000;
	        		$user->gems = 10;
	        		$user->is_new = 1;
	        		$user->save();
					$wx_user = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
					if ($wx_user) {//已经是公众号用户
		        		$wx_user->unionid = $origin_info['unionid'];
		        		$wx_user->nickname = $origin_info['nickname'];
		        		$wx_user->headimgurl = $origin_info['headimgurl'];
		        		$wx_user->save();
					} else {//注册公众号
		        		$wx_user = new WxPublicUser;
		        		$wx_user->unionid = $origin_info['unionid'];
		        		$wx_user->openid = $origin_info['openid'];
		        		$wx_user->nickname = $origin_info['nickname'];
		        		$wx_user->headimgurl = $origin_info['headimgurl'];
		        		$wx_user->save();
					}
				}
				return redirect("http://fir.im/91z4");
			}
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'WC_CHAMPION') {//世界杯冠军竞猜
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if (!$user) {//新游戏用户了
	        		$user = new User;
	        		$user->userid = $this->generateUserId();
	        		$user->account = 'wx_'.$origin_info['unionid'];
	        		$user->open_id = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimg = $origin_info['headimgurl'];
	        		$user->name = base64_encode($origin_info['nickname']);
	        		$user->lv = 1;
	        		$user->coins = 1000;
	        		$user->gems = 10;
	        		$user->is_new = 1;
	        		$user->save();
				}
				$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
				if ($wx_fans) {
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->save();
				} else {
					$wx_fans = new WxPublicUser;
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->openid = $origin_info['openid'];
					$wx_fans->save();
				}
		        $app = new Application($this->config);
		        $userService = $app->user;
		        $suser = $userService->get($wx_fans->openid);
		        $subscribe = $suser->subscribe;
		        if ($subscribe==0) {
		            return redirect('/mobile/guanzhu');
		        }

				return redirect('/mobile/worldcup/champion_choose/'.$user->id);
			}
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'WC_DAYGUESS') {//世界杯每日竞猜
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if (!$user) {//新游戏用户了
	        		$user = new User;
	        		$user->userid = $this->generateUserId();
	        		$user->account = 'wx_'.$origin_info['unionid'];
	        		$user->open_id = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimg = $origin_info['headimgurl'];
	        		$user->name = base64_encode($origin_info['nickname']);
	        		$user->lv = 1;
	        		$user->coins = 1000;
	        		$user->gems = 10;
	        		$user->is_new = 1;
	        		$user->save();
				}
				$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
				if ($wx_fans) {
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->save();
				} else {
					$wx_fans = new WxPublicUser;
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->openid = $origin_info['openid'];
					$wx_fans->save();
				}
		        $app = new Application($this->config);
		        $userService = $app->user;
		        $suser = $userService->get($wx_fans->openid);
		        $subscribe = $suser->subscribe;
		        if ($subscribe==0) {
		            return redirect('/mobile/guanzhu');
		        }

				return redirect('/mobile/worldcup/day_choose/'.$user->id);
			}
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'INVITE_FRIEND') {//代理邀请用户加入亲友圈
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if (Session::has('wx_invite_agent_id')) {
					$agent_id = Session::get('wx_invite_agent_id');
				} else {
					$msg = '代理不存在！';
					return view('mobile.layout.error', compact('msg'));
				}
				if (!$user) {//新游戏用户
	        		$user = new User;
	        		$user->userid = $this->generateUserId();
	        		$user->account = 'wx_'.$origin_info['unionid'];
	        		$user->open_id = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimg = $origin_info['headimgurl'];
	        		$user->name = base64_encode($origin_info['nickname']);
	        		$user->daili_id = $agent_id;
	        		$user->lv = 1;
	        		$user->coins = 1000;
	        		$user->gems = 10;
	        		$user->is_new = 1;
	        		$user->save();
				} else {//老用户
					$exist = ClubUser::where(['userid' => $user->userid])->whereIn('state', [0, 10, 999])->first();
					if ($exist) {
						$club = Club::where(['club_id' => $exist->club_id])->whereIn('type', [2,3,4,5])->first();
						if ($club) {//已经加入过会员亲友圈了
							$msg = '您已经加入过亲友圈了，不能再次加入！';
							return view('mobile.layout.error', compact('msg'));
						}
					}
					if ($user->daili_id != 0 && $user->daili_id != $agent_id) {
						$msg = '您不是此代理发展的玩家，不能加入此代理的亲友圈！';
						return view('mobile.layout.error', compact('msg'));
					}
				}
				$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
				if ($wx_fans) {
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->save();
				} else {
					$wx_fans = new WxPublicUser;
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->openid = $origin_info['openid'];
					$wx_fans->save();
				}
				if (Session::has('wx_invite_club_id')) {
					$club_id = Session::get('wx_invite_club_id');//俱乐部id
					Session::forget('wx_invite_club_id');
					$c_user = new ClubUser;
					$c_user->club_id = $club_id;
					$c_user->userid = $user->userid;
					$c_user->join_time = time();
					$c_user->state = 0;
					$c_user->save();
					if (Session::has('wx_invite_agent_id')) {
						$agent_id = Session::get('wx_invite_agent_id');
						Session::forget('wx_invite_agent_id');
						$agent = Agent::where(['id' => $agent_id])->first();
						if ($agent) {
					        $app = new Application($this->config);
				            $notice = $app->notice;
				            $openId = $agent->open_id;
    		            	$userService = $app->user;
				            $member = $userService->get($openId);
				            $subscribe = $member->subscribe;
				            if ($subscribe) {
					            $templateId = 'ocSxTEYwwyxiYPEyFMj4XOY6ZJCx-5Qj250w9P7ayWU';
					            $url = url("http://user.leyougame.cc/mobile/agent/friend_circle/".$agent->id);
					            $data = array(
					                "first" => "有玩家申请加入亲友圈，请尽快审核!",
					                "keyword1" => date('Y-m-d H:i', time()),
					                "keyword2" => base64_decode($user->name),
					                "remark" => "查看详情!",
					            );
					            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
					        }  
						}
					}
					return redirect('/mobile/guanzhu');
				} else {
					$msg = '俱乐部不存在，无法加入！';
					return view('mobile.layout.error', compact('msg'));
				}
			}
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'MENU_SHARE') {//分享朋友或朋友圈
			$agentid = Session::get('wx_menu_share_id');
			if ($agentid) {
				if ($origin_info) {
					$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
					if ($user) {//已经是游戏用户了
						$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
						if ($wx_fans) {
							$wx_fans->unionid = $origin_info['unionid'];
							$wx_fans->agent_id = $agentid;
							$wx_fans->nickname = $origin_info['nickname'];
							$wx_fans->headimgurl = $origin_info['headimgurl'];
							$wx_fans->save();
						}
					} else {
		        		$user = new User;
		        		$user->userid = $this->generateUserId();
		        		$user->account = 'wx_'.$origin_info['unionid'];
		        		$user->open_id = $origin_info['openid'];
		        		$user->nickname = $origin_info['nickname'];
		        		$user->headimg = $origin_info['headimgurl'];
		        		$user->name = base64_encode($origin_info['nickname']);
		        		$user->daili_id = $agentid;
		        		$user->lv = 1;
		        		$user->coins = 1000;
		        		$user->gems = 10;
		        		$user->is_new = 1;
		        		$user->save();
						$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
						if ($wx_fans) {
							$wx_fans->unionid = $origin_info['unionid'];
							$wx_fans->agent_id = $agentid;
							$wx_fans->nickname = $origin_info['nickname'];
							$wx_fans->headimgurl = $origin_info['headimgurl'];
							$wx_fans->save();
						}
						$agent = Agent::where(['id' => $user->daili_id])->first();
						if ($agent) {
					        $app = new Application($this->config);
				            $notice = $app->notice;
				            $openId = $agent->open_id;
    		            	$userService = $app->user;
				            $member = $userService->get($openId);
				            $subscribe = $member->subscribe;
				            if ($subscribe) {
					            $templateId = 'ThzL02D7i_RDlU2_qaKRbqcahMIUWRp4yOlHICEwlHo';
					            $url = url("/mobile/index");
					            $data = array(
					                "first" => "有新玩家与您成功完成绑定!",
					                "keyword1" => $user->nickname,
					                "keyword2" => date('Y-m-d H:i', time()),
					                "remark" => "查看详情!",
					            );
					            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
					        }    	
						}
					}
					return redirect('/mobile/guanzhu');	
				}
			}	
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'DRAW_LOTTERY') {//转盘抽奖
			if ($origin_info) {
				$user = User::where(['account' => 'wx_'.$origin_info['unionid']])->first();
				if (!$user) {//新游戏用户了
	        		$user = new User;
	        		$user->userid = $this->generateUserId();
	        		$user->account = 'wx_'.$origin_info['unionid'];
	        		$user->open_id = $origin_info['openid'];
	        		$user->nickname = $origin_info['nickname'];
	        		$user->headimg = $origin_info['headimgurl'];
	        		$user->name = base64_encode($origin_info['nickname']);
	        		$user->lv = 1;
	        		$user->coins = 1000;
	        		$user->gems = 10;
	        		$user->is_new = 1;
	        		if (Session::has('wx_share_lottery_invite_id')) {
	        			$user->invite_id = Session::get('wx_share_lottery_invite_id');
	        		}
	        		$user->save();
				}
				$wx_fans = WxPublicUser::where(['openid' => $origin_info['openid']])->first();
				if ($wx_fans) {
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->save();
				} else {
					$wx_fans = new WxPublicUser;
					$wx_fans->unionid = $origin_info['unionid'];
					$wx_fans->nickname = $origin_info['nickname'];
					$wx_fans->headimgurl = $origin_info['headimgurl'];
					$wx_fans->openid = $origin_info['openid'];
					$wx_fans->save();
				}
		        $app = new Application($this->config);
		        $userService = $app->user;
		        $suser = $userService->get($wx_fans->openid);
		        $subscribe = $suser->subscribe;
		        if ($subscribe==0) {
		            return redirect('/mobile/guanzhu');
		        }

				return redirect('/mobile/lottery/index/'.$user->id);
			}			
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'DAY_PAYMENT') {//每日支付
			if ($origin_info) {
				$agent = Agent::where(['unionid' => $origin_info['unionid']])->first();
				Auth::guard('mobile')->login($agent);
				
				return redirect('/mobile/agent/day_pay');
			}	
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'SUPER_AGENT_APPLY') {//超级代理申请
			if ($origin_info) {
				$agent = SuperAgent::where(['unionid' => $origin_info['unionid']])->first();
				if ($agent) {//有代理信息
					if ($agent->status == 1) {//通过了去首页
						//去代理首页
						Auth::guard('agent')->login($agent);
						return redirect('/mobile/superagent/index');
					} elseif ($agent->status == 0) {//审核中
						//审核中
						return view('mobile.agent.audit');
					} else {
						//去申请页面
						return view('mobile.superagent.apply', compact('origin_info'));
					}
				} else {//没有代理信息去申请
					return view('mobile.superagent.apply', compact('origin_info'));
				}
			}								
		} elseif (isset($_REQUEST['state']) && $_REQUEST['state'] == 'AGENT_LOGIN') {//推广员登录
			if ($origin_info) {
				$agent = Agent::where(['unionid' => $origin_info['unionid']])->first();
				if ($agent) {
					if ($agent->status == 1) {
						Auth::guard('mobile')->login($agent);
						return redirect('/mobile/agent/index/'.$agent->id);
					} else {
						$msg = '您的推广员申请还在审核中!';
						return view('mobile.layout.error', compact('msg'));
					}
				} else {
					$msg = '您还没有注册推广员，无法登录!';
					return view('mobile.layout.error', compact('msg'));
				}
			}	
		} else {//代理注册
			if ($origin_info) {
				$agent = Agent::where(['unionid' => $origin_info['unionid']])->first();
				if ($agent) {//有代理信息
					if ($agent->status == 1) {
						//去代理首页
						Auth::guard('mobile')->login($agent);
						return redirect('/mobile/agent/index/'.$agent->id);
					} elseif ($agent->status == 2) {
						//被驳回了
						return view('mobile.agent.reject', compact('agent'));
					} elseif ($agent->status == 0) {
						//审核中
						return view('mobile.agent.audit'); 
					} else {
						//去申请页面
						return view('mobile.agent.apply', compact('origin_info'));
					}
				} else {//没有代理信息
					//去申请代理
					return view('mobile.agent.apply', compact('origin_info'));
				}
			}
		}

		return;
	}

	/**
	 * [enterAgent description]
	 * @return [type] [description]
	 */
	public function enterAgent(User $user)
	{
		return view('mobile.agent.enter', compact('user'));
	}

	/**
	 * [storeEnter description]
	 * @return [type] [description]
	 */
	public function storeEnter(User $user, Request $request)
	{
        $validator = Validator::make($request->input(), [
            'agent_id' => 'required'
        ],[
            'agent_id.required' => '推广员ID不能为空'
        ]);
        $exist = Agent::where(['unionid' => substr($user->account, 3)])->first();
        if ($exist) {
	        $validator->after(function($validator){
	            $validator->errors()->add('agent_id', '您已经注册推广员了, 无法完成绑定!');
	        });		
        }
        $agent = Agent::where(['id' => $request->input('agent_id')])->first();
        if (!$agent) {
	        $validator->after(function($validator){
	            $validator->errors()->add('agent_id', '推广员ID不正确!');
	        });	
        }
        if ($agent->pid == 0) {
	        $validator->after(function($validator){
	            $validator->errors()->add('agent_id', '不能绑定区域推广员!');
	        });	
        }
        if ($validator->passes()) {
        	$user->agent_id = $request->input('agent_id');
        	$user->save();

	    	return views('mobile.agent.bindSuc');
        } else {
        	return Redirect::back()->withInput()->withErrors($validator->errors());
        }
	}

	/**
	 * [getCode description]
	 * @return [type] [description]
	 */
	public function getCode(Request $request)
	{
        $validator = Validator::make($request->input(), [
            'mobile' => 'required|regex:/^1[3456789][0-9]{9}$/'
        ],[
            'mobile.required' => '手机号不能为空',
            'mobile.regex' => '手机号错误'
        ]);
        if ($validator->fails()) {
            return ['flag' => false, 'message' => $validator->errors()->first('mobile')];
        }
		$mobile = $request->input('mobile');
		$code = rand(10000, 99999);
		$result = Sms::make()->to($mobile)->content('【乐游手游】您的验证码是'.$code)->send();
		if ($result['success']) {
			PhoneValidate::create(['phone' => $request->input('mobile'), 'code' => $code]);

    		return [
        		'flag' => true
        	];
        } else {

        	return [
        		'flag' => false
        	];
        }
	}

	/**
	 * [cashCode description]
	 * @return [type] [description]
	 */
	public function cashCode(Request $request)
	{
        $validator = Validator::make($request->input(), [
            'mobile' => 'required|regex:/^1[34578][0-9]{9}$/'
        ],[
            'mobile.required' => '手机号不能为空',
            'mobile.regex' => '手机号错误',
        ]);
        if ($validator->fails()) {
            return ['flag' => false, 'message' => $validator->errors()->first('mobile')];
        }
		$mobile = $request->input('mobile');
		$code = rand(10000, 99999);
		$result = Sms::make()->to($mobile)->content('【乐游手游】您的验证码是'.$code)->send();
		if ($result['success']) {
			PhoneValidate::create(['phone' => $request->input('mobile'), 'code' => $code]);

    		return [
        		'flag' => true
        	];
        } else {

        	return [
        		'flag' => false
        	];
        }
	}

	/**
	 * [apply description]
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function apply(Request $request)
	{
        $validator = Validator::make($request->all(), [
        	'realname' => 'required',
        	'address' => 'required',
        	'mobile' => 'required',
        	'code' => 'required',
        	'open_id' => 'required',
        	'unionid' => 'required',
        	'nickname' => 'required',
        	'avatar' => 'required'
        ], [
        	'realname.required' => '请填写真实姓名',
        	'address.required' => '请填写代理地址',
        	'mobile.required' => '请填写手机号码',
        	'code.required' => '请填写验证码',
        ]);
        $exist = PhoneValidate::where('phone', '=', $request->input('mobile'))->where('code', '=', $request->input('code'))->first();
		if (!$exist) {
	        $validator->after(function($validator){
	            $validator->errors()->add('code', '验证码错误');
	        });
		}

        if ($validator->passes()) {
        	$user_exist = User::where(['account' => 'wx_'.$request->input('unionid')])->first();
        	if (!$user_exist) {//没有成为游戏用户
        		/*注册新的游戏用户*/
        		$user = new User;
        		$user->userid = $this->generateUserId();
        		$user->account = 'wx_'.$request->input('unionid');
        		$user->open_id = $request->input('open_id');
        		$user->nickname = $request->input('nickname');
        		$user->headimg = $request->input('avatar');
        		$user->lv = 1;
        		$user->coins = 1000;
        		$user->gems = 10;
        		$user->is_new = 1;
        		$user->save();
        	}
        	$agent = Agent::where(['unionid' => $request->input('unionid')])->first();
        	if (!$agent) {
        		$agent = new Agent;
        	}
        	$agent->mobile = $request->input('mobile');
        	$agent->address = $request->input('address');
        	$agent->unionid = $request->input('unionid');
        	$agent->open_id = $request->input('open_id');
        	$agent->realname = $request->input('realname');
        	$agent->shenqing_time = time();
        	$agent->avatar = $request->input('avatar');
        	$agent->nickname = $request->input('nickname');
        	if ($request->input('pid')) {
        		$agent->pid = $request->input('pid');
        		$agent->level = 2;
        	}
        	if (Session::has('superagent_id')) {
        		$agent->superagent_id = Session::get('superagent_id');
        		Session::forget('superagent_id');
        	}
        	$agent->status = 0;
    		DB::beginTransaction();
	    	try{
	    		$agent->save();
	    		$exist->delete();
	        	DB::commit();
	        	$top_agent = Agent::where(['id' => $agent->pid])->first();
	        	if ($top_agent) {
			        $app = new Application($this->config);
		            $notice = $app->notice;
		            $openId = $top_agent->open_id;
	            	$userService = $app->user;
		            $member = $userService->get($openId);
		            $subscribe = $member->subscribe;
		            if ($subscribe) {
			            $templateId = '-OaDbgMkWS2YAhgjFSl3PSzIJ87tj4bZqIBzBWKWvwg';
			            $url = "http://user.leyougame.cc/mobile/agent/audit_list/".$top_agent->id;
			            $data = array(
			                "first" => "您有新的推广员申请入驻！",
			                "keyword1" => $agent->realname,
			                "keyword2" => date("Y-m-d H:i", time()),
			                "keyword3" => "",
			                "remark" => "麻烦尽快审核通过！",
			            );
			            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
			        }    
	        	}

	        	Auth::guard('mobile')->login($agent);
	        	return ['flag' => true];
	    	} catch (Exception $e) {
	    		DB::rollback();
	  			return redirect('/mobile/index');
	    	}
        } else {
        	$errors = $validator->errors();
        	foreach ($errors->messages as $val) {
        		$error = $val[0];
        	}
        	return ['flag' => false, 'msg' => $error];
        }
	}

	/**
	 * 申请3级代理
	 */
	public function threeapply(Request $request)
	{
        $validator = Validator::make($request->all(), [
        	'realname' => 'required',
        	'address' => 'required',
        	'mobile' => 'required',
        	'code' => 'required',
        	'open_id' => 'required',
        	'unionid' => 'required',
        	'nickname' => 'required',
        	'avatar' => 'required'
        ], [
        	'realname.required' => '请填写真实姓名',
        	'address.required' => '请填写代理地址',
        	'mobile.required' => '请填写手机号码',
        	'code.required' => '请填写验证码',
        ]);
        $exist = PhoneValidate::where('phone', '=', $request->input('mobile'))->where('code', '=', $request->input('code'))->first();
		if (!$exist) {
	        $validator->after(function($validator){
	            $validator->errors()->add('code', '验证码错误');
	        });
		}

        if ($validator->passes()) {
        	$user_exist = User::where(['account' => 'wx_'.$request->input('unionid')])->first();
        	if (!$user_exist) {//没有成为游戏用户
        		/*注册新的游戏用户*/
        		$user = new User;
        		$user->userid = $this->generateUserId();
        		$user->account = 'wx_'.$request->input('unionid');
        		$user->open_id = $request->input('open_id');
        		$user->nickname = $request->input('nickname');
        		$user->headimg = $request->input('avatar');
        		$user->lv = 1;
        		$user->coins = 1000;
        		$user->gems = 10;
        		$user->is_new = 1;
        		$user->save();
        	}
        	$agent = Agent::where(['unionid' => $request->input('unionid')])->first();
        	if (!$agent) {
        		$agent = new Agent;
        	}
        	$agent->mobile = $request->input('mobile');
        	$agent->address = $request->input('address');
        	$agent->unionid = $request->input('unionid');
        	$agent->open_id = $request->input('open_id');
        	$agent->realname = $request->input('realname');
        	$agent->shenqing_time = time();
        	$agent->avatar = $request->input('avatar');
        	$agent->nickname = $request->input('nickname');
        	if ($request->input('pid')) {
        		$agent->pid = $request->input('pid');
        	}
        	if (Session::has('superagent_id')) {
        		$agent->superagent_id = Session::get('superagent_id');
        		Session::forget('superagent_id');
        	}
        	$agent->level = 3;
        	$agent->status = 0;
    		DB::beginTransaction();
	    	try{
	    		$agent->save();
	    		$exist->delete();
	        	DB::commit();
	        	$top_agent = Agent::where(['id' => $agent->pid])->first();
	        	if ($top_agent) {
			        $app = new Application($this->config);
		            $notice = $app->notice;
		            $openId = $top_agent->open_id;
	            	$userService = $app->user;
		            $member = $userService->get($openId);
		            $subscribe = $member->subscribe;
		            if ($subscribe) {
			            $templateId = '-OaDbgMkWS2YAhgjFSl3PSzIJ87tj4bZqIBzBWKWvwg';
			            $url = "http://user.leyougame.cc/mobile/agent/audit_list/".$top_agent->id;
			            $data = array(
			                "first" => "您有新的推广员申请入驻！",
			                "keyword1" => $agent->realname,
			                "keyword2" => date("Y-m-d H:i", time()),
			                "keyword3" => "",
			                "remark" => "麻烦尽快审核通过！",
			            );
			            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
			        }    
	        	}

	        	Auth::guard('mobile')->login($agent);
	        	return ['flag' => true];
	    	} catch (Exception $e) {
	    		DB::rollback();
	  			return redirect('/mobile/index');
	    	}
        } else {
        	$errors = $validator->errors();
        	foreach ($errors->messages as $val) {
        		$error = $val[0];
        	}
        	return ['flag' => false, 'msg' => $error];
        }
	}

	/**
	 * [superApply description]
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function superApply(Request $request)
	{
        $validator = Validator::make($request->all(), [
        	'realname' => 'required',
        	'address' => 'required',
        	'mobile' => 'required',
        	'code' => 'required',
        	'open_id' => 'required',
        	'unionid' => 'required',
        	'nickname' => 'required',
        	// 'avatar' => 'required'
        ], [
        	'realname.required' => '请填写真实姓名',
        	'address.required' => '请填写代理地址',
        	'mobile.required' => '请填写手机号码',
        	'code.required' => '请填写验证码',
        ]);
        $exist = PhoneValidate::where('phone', '=', $request->input('mobile'))->where('code', '=', $request->input('code'))->first();
		if (!$exist) {
	        $validator->after(function($validator){
	            $validator->errors()->add('code', '验证码错误');
	        });
		}

        if ($validator->passes()) {
        	$agent = SuperAgent::where(['unionid' => $request->input('unionid')])->first();
        	if (!$agent) {
        		$agent = new SuperAgent;
        	}
        	$agent->mobile = $request->input('mobile');
        	$agent->address = $request->input('address');
        	$agent->unionid = $request->input('unionid');
        	$agent->openid = $request->input('open_id');
        	$agent->realname = $request->input('realname');
        	$agent->apply_at = date('Y-m-d H:i:s', time());
        	if ($request->input('avatar')) {
        		$agent->avatar = $request->input('avatar');
        	}
        	$agent->nickname = $request->input('nickname');
        	$agent->status = 0;
    		DB::beginTransaction();
	    	try{
	    		$agent->save();
	    		$exist->delete();
	        	DB::commit();

	        	Auth::guard('agent')->login($agent);
	        	return ['flag' => true];
	    	} catch (Exception $e) {
	    		DB::rollback();
	  			return redirect('/mobile/superagent/index');
	    	}
        } else {
        	$errors = $validator->errors();
        	foreach ($errors->messages as $val) {
        		$error = $val[0];
        	}
        	return ['flag' => false, 'msg' => $error];
        }
	}

	/**
	 * [generateUserId description]
	 * @return [type] [description]
	 */
	protected function generateUserId()
	{
		$id = rand(100000, 999999);
		$exist = User::where(['userid' => $id])->first();
		if ($exist) {
			$id = $this->generateUserId();
		}
		return $id;
	}

	/**
	 * [reapply description]
	 * @return [type] [description]
	 */
	public function reapply(Agent $agent)
	{
		$origin_info['openid'] = $agent->open_id;
		$origin_info['unionid'] = $agent->unionid;
		$origin_info['nickname'] = $agent->nickname;
		$origin_info['headimgurl'] = $agent->avatar;
		return view('mobile.agent.apply', compact('origin_info'));
	}

	/**
	 * [fillAddress description]
	 * @return [type] [description]
	 */
	public function fillAddress(WxPublicUser $wxuser, Request $request)
	{
		$city = Region::where('region_name', 'like', '%'.$request->input('cityName').'%')->first();
		if ($city) {
			$wxuser->city = $city->id;
			$wxuser->save();
		}
		return ['flag' => true];
	}

	/**
	 * [downloadGame description]
	 * @param  WxPublicUser $wxuser [description]
	 * @return [type]               [description]
	 */
	public function downloadGame(User $user)
	{
		return view('mobile.agent.download', compact('user'));
	}

	/**
	 * [agreement description]
	 * @return [type] [description]
	 */
	public function agreement()
	{
		return view('mobile.agent.agreement');
	}

	/**
	 * [userLocation 获取用户的地址]
	 * @return [type] [description]
	 */
	public function userLocation(Request $request, User $user)
	{
		if ($user->is_static == 1) {//已经统计过了
			return ['flag' => true];
		}
		$lat = $request->input('lat');
		$lng = $request->input('lng');
		$url = "http://api.map.baidu.com/geocoder/v2/?location=$lat,$lng&ak=2u4zZODA0DuGZi7vFKaXKgq2KkaMrP6k&output=json";
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
    	curl_setopt($curl, CURLOPT_HEADER, FALSE);    //表示需要response header
		//设置获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//执行命令
		$data = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);
		$data = json_decode($data, true);
		if ($data['status'] == 0) {//成功返回
			$city = $data['result']['addressComponent']['city'];//城市名称
			if (strlen($city) > 2) {
				$city = mb_substr($city, 0, 2);
			}
			$region = Region::where('region_name', 'LIKE', '%'.$city.'%')->first();
			if ($region) {
				$date = strtotime(date("Y-m-d"), time());
				$exist = UserStatistic::where(['city' => $region->id, 'date' => $date, 'type' => 1])->first();
				if ($exist) {//存在
					$exist->number += 1;
				} else {//不存在
					$exist = new UserStatistic;
					$exist->date = $date;
					$exist->city = $region->id;
					$exist->city_name = $region->region_name;
					$exist->type = 1;
					$exist->number = 1;
				}
				$exist->save();
				$user->is_static = 1;
				$user->save();
			}
		}
		return ['flag' => true];	
	}

	/**
	 * [firstExplain description]
	 * @return [type] [description]
	 */
	public function firstExplain()
	{
		return view('mobile.agent.firstExplain');
	}

	/**
	 * [secondExplain description]
	 * @return [type] [description]
	 */
	public function secondExplain()
	{
		return view('mobile.agent.secondExplain');
	}

	/**
	 * [bindMsg description]
	 * @return [type] [description]
	 */
	public function bindMsg(Request $request)
	{
        $validator = Validator::make($request->all(), [
        	'userid' => 'required|numeric|min:1',
        	'agent_id' => 'required|numeric|min:1'
        ], [
        	'userid.required' => '用户id不为空',
        	'userid.numeric' => '用户id为整数',
        	'userid.min' => '用户id错误',
        	'agent_id.required' => '代理id不为空',
        	'agent_id.numeric' => '代理id为整数',
        	'agent_id.min' => '代理id错误'
        ]);
        if ($validator->passes()) {
        	$user = User::where(['userid' => $request->input('userid')])->first();
        	$username = $user->nickname ? $user->nickname : base64_decode($user->name);
        	$agent = Agent::where(['id' => $request->input('agent_id')])->first();
        	if ($agent && $username) {
		        $app = new Application($this->config);
		        $notice = $app->notice;
		        $openId = $agent->open_id;
	    		$userService = $app->user;
	            $member = $userService->get($openId);
	            $subscribe = $member->subscribe;
	            if ($subscribe) {
			        $templateId = 'ThzL02D7i_RDlU2_qaKRbqcahMIUWRp4yOlHICEwlHo';
			        $url = url("/mobile/index");
			        $data = array(
			            "first" => "有新玩家与您成功完成绑定!",
			            "keyword1" => $username,
			            "keyword2" => date('Y-m-d H:i', time()),
			            "remark" => "查看详情!",
			        );
			        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
			    }    
        	}

	        return ['flag' => true];
        } else {
        	return ['flag' => false, 'msg' => $validator->errors()];
        }
	}

	/**
	 * [sendMsg description]
	 * @return [type] [description]
	 */
	public function sendMsg($wx_user, $msg)
	{
	    $app = new Application($this->config);
	    $userService = $app->user;
	    $suser = $userService->get($wx_user->openid);
	    $subscribe = $suser->subscribe;
	    if ($subscribe != 0) {
	        $notice = $app->notice;
	        $openId = $wx_user->openid;
	        $templateId = 'N_YwxARMlPkV8gsKEE68UUQAcDWRDbIbX7FzUvIgTQ8';
	        $url = "";
	        $data = array(
	            "first" => $msg['message'],
	            "keynote1" => $msg['message'],
	            "keynote2" => $msg['money']."元红包",
	            "remark" => "祝您游戏愉快!",
	        );
	        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
	    }  
	}

	/**
	 * [isSubscribe 判断用户是否关注公众号]
	 * @return boolean [description]
	 */
	public function isSubscribe(Request $request)
	{
		if (!$request->input('userid')) {
			return ['flag' => false, 'msg' => 'userid不能为空'];
		}
		$user = User::where(['userid' => $request->input('userid')])->first();
    	if ($user) {
        	$wx_user = WxPublicUser::where(['unionid' => substr($user->account, 3)])->first();
        	if ($wx_user) {
			    $app = new Application($this->config);
			    $userService = $app->user;
			    $suser = $userService->get($wx_user->openid);
			    $subscribe = $suser->subscribe;
			    if ($subscribe != 0) {
			    	return ['flag' => true];
			    } else {
			    	return ['flag' => false, 'msg' => '没有关注!'];
			    }
        	} else {
        		return ['flag' => false, 'msg' => '没有关注!'];
        	}
    	} else {
    		return ['flag' => false, 'msg' => '找不到用户!'];
    	}
	}

	/**
	 * [newActive 最新活动]
	 * @return [type] [description]
	 */
	public function newActive()
	{
		return view('mobile.agent.newactive');
	}

	/**
	 * [guanzhu 关注公众号]
	 * @return [type] [description]
	 */
	public function guanzhu()
	{
		return view('mobile.worldcup.guanzhu');
	}

	/**
	 * [bigWinner 大赢家消息通知]
	 * @return [type] [description]
	 */
	public function bigWinner(Request $request)
	{
		if (!$request->input('userid')) {
			return ['flag' => false, 'msg' => '用户id不能为空'];
		}
		if (!$request->input('message')) {
			return ['flag' => false, 'msg' => '通知信息不能为空'];
		}
		$user = User::where(['userid' => $request->input('userid')])->first();
		if (!$user) {
			return ['flag' => false, 'msg' => '用户不存在'];
		}
		if ($user->daili_id == 0) {
			return ['flag' => false, 'msg' => '用户没有推广代理'];
		}
		$agent = Agent::where(['id' => $user->daili_id])->first();
		if ($agent) {
		    $app = new Application($this->config);
		    $userService = $app->user;
		    $suser = $userService->get($agent->open_id);
		    $subscribe = $suser->subscribe;
		    if ($subscribe != 0) {
		        $notice = $app->notice;
		        $openId = $agent->open_id;
		        $templateId = 'FgZhSRfW8ro4KUd6gyL-Jloa2ciGLinem_dmqbhKqw0';
		        $url = "";
		        $data = array(
		            "first" => $request->input('message'),
		            "result" => "有效",
		            "time" => date("Y-m-d H:i", time()),
		            "remark" => "祝您游戏愉快!",
		        );
		        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
		        $log = new WinnerNotice;
		        $log->userid = $request->input('userid');
		        $log->agentid = $agent->id;
		        $log->message = $request->input('message');
		        $log->save();
		    }  
		}
		return ['flag' => true];
	}

	/**
	 * 会员亲友圈加入通知
	 */
	public function friendCircleJoin(Request $request)
	{
		$apply_id = $request->input('apply_id');//申请人id
		$manager_id = $request->input('manager_id');//群主id
		if (!$apply_id) {
			return ['error' => 1000, 'msg' => '申请人id不能为空'];
		}
		if (!$manager_id) {
			return ['error' => 1000, 'msg' => '群主id不能为空'];
		}
		$apply = User::where(['userid' => $apply_id])->first();
		if (!$apply) {
			return ['error' => 1001, 'msg' => '申请人id错误'];
		}
		$manager = User::where(['userid' => $manager_id])->first();
		if (!$manager) {
			return ['error' => 1001, 'msg' => '群主id错误'];
		}
		$daili = Agent::where(['unionid' => substr($manager->account, 3)])->first();
		if (!$daili) {
			return ['error' => 1001, 'msg' => '群主id错误'];
		}
	    $app = new Application($this->config);
	    $userService = $app->user;
	    $suser = $userService->get($daili->open_id);
	    $subscribe = $suser->subscribe;
	    if ($subscribe != 0) {
	        $notice = $app->notice;
	        $openId = $daili->open_id;
	        $templateId = 'ocSxTEYwwyxiYPEyFMj4XOY6ZJCx-5Qj250w9P7ayWU';
	        $url = "";
	        $data = array(
	            "first" => "玩家：".base64_decode($apply->name)." 申请加入您的亲友圈啦！",
	            "keyword1" => date('Y-m-d H:i', time()),
	            "keyword2" => base64_decode($apply->name),
	            "remark" => "继续努力扩展您的圈子吧!",
	        );
	        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
	        return ['error' => 0];
	    }
	    return ['error' => 1002, 'msg' => '未知错误'];
	}

	public function test()
	{
		return view('mobile.test.index');
	}

}	